using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
//using ID3;
using ID3Sharp;

namespace JamD3
{
    public partial class llCopySelectedTextToTb : Form
    {
        public llCopySelectedTextToTb()
        {
            InitializeComponent();

        }

        ConcertText ctFile;
        String delimiter = "\r\n";
        bool codeSpawn = false;
        private void btnStartWizard_Click(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            ctFile.AlbumTitle = tbSelection.Text;
        }

        private void btnCopyToSingleLineTB_Click(object sender, EventArgs e)
        {

        }

        private void llOpenInformationFile_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    ctFile = new ConcertText();
                    ctFile.LoadConcertTextFile(ofd.FileName);
                    tbTextFile.Text = ctFile.FileContents;
                }

                catch (Exception exc)
                {
                    MessageBox.Show(exc.Message + "\r\n\r\nPlease Try Opening File Again.", "Error Opening Selected File");
                    return;
                }

                tcMain.Enabled = true;
            }
            //TODO: Figure out why I did this.
            /*else
            {
                if (ctFile.FileContents.Equals("") || ctFile.TextFilePath.Equals(""))
                {
                    tcMain.Enabled = false;
                }
            }*/
        }



        private void llCopyToProperty_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            String newText = tbSelection.Text.Trim();
            if (rbArtist.Checked)
            {

                ctFile.AlbumArtist = newText;
            }
            else if (rbTitle.Checked)
            {
                //if (newText.Length > 30)
                //{
                //    MessageBox.Show("Album title cannot exceed 30 characters.");
                //    return;
                //}
                //else
                {

                    ctFile.AlbumTitle = newText;

                }
            }
            else if (rbYear.Checked)
            {
                //Perform Validation
                if (IsValidYear(newText))
                {
                    ctFile.AlbumYear = newText;
                }

                else
                {
                    MessageBox.Show("Entry is not a valid year.\r\nPlease review the entry and try again.", "Error");
                    return;
                }
            }
            else //default case
            {
                MessageBox.Show("Please select a destination radio button before continuing.", "Error");
                return;
            }
            tbSelection.Text = "";
            RefreshLabels();
            return;
        }

        private void RefreshLabels()
        {
            lblTitle.Text = ctFile.AlbumTitle;
            lblYear.Text = ctFile.AlbumYear;
            lblArtist.Text = ctFile.AlbumArtist;
        }

        private static bool IsValidYear(string p)
        {
            try
            { Convert.ToInt32(p); }
            catch
            {
                return false;
            }
            return true;
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            tbSelection.Text = tbTextFile.SelectedText.Replace("\r\n", " - ");
        }

        private void llAppendTextToTb_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            tbSelection.Text += tbTextFile.SelectedText.Replace("\r\n", " - ").Trim();
        }

        private void linkLabel3_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            var del = new Delimiter();
            del.DelimiterString = delimiter;
            if (del.ShowDialog() == DialogResult.OK)
            {
                delimiter = del.DelimiterString;
                lblDelimiter.Text = ("Delimiter: " + delimiter);
            }

        }

        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            String[] delimiters = { delimiter };
            String[] ListOfTracks = tbTextFile.SelectedText.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
            codeSpawn = true;
            cbNumberedTrackPrefixes.Checked = AI_DoTracksHaveAPreceedingNumber(ListOfTracks);

            for (int i = 0; i < ListOfTracks.Length; i++)
            {
                string s = ListOfTracks[i];
                lbTrackText.Items.Add(s.Trim());
            }

            RecalcTrackNumbers();
        }

        private void RecalcTrackNumbers()
        {
            lblNumberOfTracks.Text = lbTrackText.Items.Count + " Items";
        }

        private bool AI_DoTracksHaveAPreceedingNumber(string[] ListOfTracks)
        {
            var numberOfTracks = ListOfTracks.Length;
            char[] delimiters = { '-', ' ', '.' };
            var weight = 0;
            var multiplier = 2;
            var endWeight = multiplier * numberOfTracks;
            var lastInt = 0;
            foreach (string track in ListOfTracks)
            {

                int iConvertedInt, nCharsToSearch = 0;
                if (track.Length >= 5)
                    nCharsToSearch = 5;
                else
                    nCharsToSearch = track.Length;

                int i = track.IndexOfAny(delimiters, 0, nCharsToSearch);
                if (i != -1)
                {
                    string substr = track.Substring(0, i);
                    try
                    {
                        iConvertedInt = Convert.ToInt32(substr);
                        weight += (multiplier / 2);
                        if (lastInt == 0)
                            lastInt = iConvertedInt;
                        else
                        {
                            if (iConvertedInt == lastInt + 1)
                            {
                                weight += (multiplier / 2);
                            }
                            lastInt = iConvertedInt;
                        }

                    }
                    catch
                    {
                        weight -= (multiplier / 2);
                    }
                    if (weight * multiplier >= endWeight)
                        return true;
                }
            }
            return false;
        }

        private void llChooseMp3Files_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Multiselect = true;
            ofd.Filter = "mp3 Audio Files (*.mp3)|*.mp3";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                foreach (string strFile in ofd.FileNames)
                {
                    lbFileText.Items.Add(strFile);
                }
            }

        }

        private void lbTrackText_Click(object sender, EventArgs e)
        {
            /*EditSongTitle est = new `SongTitle();
            est.SongTitle = (String)lbTrackText.SelectedItem;
            if (est.ShowDialog() == DialogResult.OK)
            {
                lbTrackText.Items[lbTrackText.SelectedIndex] = est.SongTitle;
            }*/
        }

        private void linkLabel4_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            bool writeTagTracks = cbTagTracks.Checked;
            for (int i = 0; i < lbFileText.Items.Count; i++)
            {

                string strFile = lbFileText.Items[i].ToString();
                ID3v2Tag tag = new ID3v2Tag();
                tag.Album = ctFile.AlbumTitle;
                tag.Artist = ctFile.AlbumArtist;
                tag.Year = ctFile.AlbumYear;
                tag.Title = lbTrackText.Items[i].ToString();
                if (writeTagTracks)
                {
                    tag.TrackNumber = i + 1;
                }
                if (lbGenre.SelectedIndex != -1)
                    tag.GenreAsInt = ID3Genre.GetGenre(lbGenre.SelectedItem.ToString());
                else if (tbCustomGenre.Text.Length != 0)
                    tag.Genre = tbCustomGenre.Text;
                tag.Comments = "ID3 tag Created by JamD3 using IDSharp libraries. JamD3 was programmed by Wes Idell. Only use mp3s for personal use - do not sell or copy mp3s for trading purposes. Trade only the original flac or shn files." +
                    tbComments.Text;
                tag.WriteTag(strFile, ID3Versions.V2_3);
                //ID3Info i3 = new ID3Info(strFile, true);
                //i3.ID3v1Info.Album = ctFile.AlbumTitle;
                //i3.ID3v1Info.Artist = ctFile.AlbumArtist;
                //i3.ID3v1Info.Year = ctFile.AlbumYear;
                //i3.ID3v1Info.Title = lbTrackText.Items[i].ToString();
                //i3.Save();
            }
        }

        /// <summary>
        /// Event handler for the context menu item with text property "Move Up"
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void miMoveUp_Click(object sender, EventArgs e)
        {
            ListBox lbSender = (ListBox)menuSongList.SourceControl;
            //if there is no 'up' from the selected item...
            if (lbSender.SelectedIndex == 0)
                return;
            //else if(everything's ok)...
            int from = lbSender.SelectedIndex;
            switchTrackPositions(lbSender, from, from - 1);
            return;
        }

        /// <summary>
        /// Handles the menu item "Move Down" onClick() event.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void miMoveDown_Click(object sender, EventArgs e)
        {
            int from;
            ListBox lbSender = (ListBox)menuSongList.SourceControl;
            //if there is no 'down' position to go to...
            if ((from = lbSender.SelectedIndex) == lbSender.Items.Count - 1)
            {
                return;
            }

            //else if (everything's alright)...
            switchTrackPositions(lbSender, from, from + 1);
        }

        /// <summary>
        /// Handles onClick() event for context menu item "Delete Item"
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void miDelete_Click(object sender, EventArgs e)
        {
            ListBox lbSender = (ListBox)menuSongList.SourceControl;
            DeleteTrackListing(lbSender,
                lbTrackText.SelectedIndex);
            RecalcMp3ListNumbers();
            RecalcTrackNumbers();
        }


        /// <summary>
        /// Switches track positions to facilitate the 'move' operations
        /// </summary>
        /// <param name="sender">ListBox on which to perform the operation.</param>
        /// <param name="from">Integer index that represents the original location</param>
        /// <param name="to">Integer indes that represents the new location</param>
        private void switchTrackPositions(ListBox sender, int from, int to)
        {
            //sanity check
            if (from > sender.Items.Count - 1 ||
                from < 0 ||
                to > sender.Items.Count - 1 ||
                to < 0)
            { return; }

            object oFrom = sender.Items[from];
            object oTo = sender.Items[to];

            sender.Items[from] = oTo;
            sender.Items[to] = oFrom;

            return;
        }



        private void DeleteTrackListing(ListBox sender, int from, int to)
        {
            //sanity check...
            #region ----------------- VALIDATION --------------------------
            if (to < from || to > sender.Items.Count - 1 || to < 0 || from > sender.Items.Count - 1 || from < 0)
            {
                return;
            }
            #endregion

            int pointer = from;
            while (pointer <= to)
            {
                //sanity check
                if (pointer >= 0 && pointer < sender.Items.Count)
                {
                    sender.Items.RemoveAt(pointer);
                }
                else
                {
                    return;
                }
                pointer++;
            }
            //successfully made it through the fxn
            return;
        }


        /// <summary>
        /// Proxy function which deletes one item in the listbox
        /// </summary>
        /// <param name="lbSender">the ListBox from which the call originated</param>
        /// <param name="p">Index of the item to delete.</param>
        private void DeleteTrackListing(ListBox lbSender, int p)
        {
            DeleteTrackListing(lbSender, p, p);
        }




        private void lbTrackText_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                ListBox lb = ((ListBox)menuSongList.SourceControl);
                int ndex = lb.IndexFromPoint(new Point(e.X, e.Y));
                if (ndex < 0 || ndex > lb.Items.Count - 1)
                    return;
                lb.SelectedIndex = ndex;
            }
        }

        private void lbTrackText_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {

                base.OnMouseClick(new MouseEventArgs(MouseButtons.Left,
                    e.Clicks, e.X, e.Y, e.Delta));
            }

        }

        private void lbTrackText_MouseDoubleClick(object sender, MouseEventArgs e)
        {

        }

        private void miEdit_Click(object sender, EventArgs e)
        {
            if (lbTrackText.SelectedIndex == -1)
                return;
            EditSongTitle est = new EditSongTitle();
            est.SongTitle = lbTrackText.SelectedItem.ToString();
            est.ShowDialog();
            if (est.DialogResult == DialogResult.OK)
            {
                lbTrackText.Items[lbTrackText.SelectedIndex] = est.SongTitle;
            }
        }

        private void linkLabel5_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {

        }

        private void tbSelection_TextChanged(object sender, EventArgs e)
        {
            lblLabelLength.Text = ((TextBox)sender).Text.Length.ToString();
        }

        private void lnklblClearListBox_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            lbFileText.Items.Clear();
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (codeSpawn)
            {
                codeSpawn = false;
                return;
            }
            if (((CheckBox)sender).Checked)
            {
                NumberTracks();
            }
            else
            {
                RemoveTrackNumbers();
            }

        }

        private void NumberTracks()
        {
            ListBox.ObjectCollection Tracks = new ListBox.ObjectCollection(lbTrackText);
            for (int nCount = 0; nCount < lbTrackText.Items.Count; nCount++)
            {
                Tracks.Add(((nCount < 9) ? "0" : "") + (nCount + 1) + ". " + lbTrackText.Items[nCount]);
            }
            lbTrackText.Items.Clear();
            lbTrackText.Items.AddRange(Tracks);
        }

        private void RemoveTrackNumbers()
        {
            ListBox.ObjectCollection Tracks = new ListBox.ObjectCollection(lbTrackText);
            for (int nCount = 0; nCount < lbTrackText.Items.Count; nCount++)
            {

                char[] delimiters = { '-', ' ', '.' };
                int i = ((string)lbTrackText.Items[nCount]).IndexOfAny(delimiters, 0, 5);
                if (i != -1)
                {
                    i++;
                    string substr = ((string)lbTrackText.Items[nCount]).Substring(i, ((string)lbTrackText.Items[nCount]).Length - i);
                    try
                    {
                        Tracks.Add(substr.Trim());
                    }
                    catch
                    {
                        throw (new Exception("Unexplained Issue with Removing Numbers"));
                    }
                }
            }
            lbTrackText.Items.Clear();
            lbTrackText.Items.AddRange(Tracks);
        }

        private void llCopySelectedTextToTb_Load(object sender, EventArgs e)
        {
            lbGenre.DataSource = ID3Genre.Genres;

        }

        private void tbCustomGenre_TextChanged(object sender, EventArgs e)
        {
            if (lbGenre.SelectedIndex != -1)
                lbGenre.SelectedIndex = -1;

        }

        private void lbGenre_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lbGenre.SelectedIndex != -1)
                tbCustomGenre.Text = "";
        }

        private void lnklblArrangeAlpha_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            ListBox.ObjectCollection objFileCollection = lbFileText.Items;

            List<string> lFiles = new List<string>();
            foreach (Object o in objFileCollection)
            {
                lFiles.Add(((string)o));
            }
            lFiles.Sort();

            lbFileText.Items.Clear();
            foreach (string s in lFiles)
            {
                lbFileText.Items.Add(s);
            }
        }

        protected void tabPageAlbum_Click(object sender, EventArgs e)
        {

        }

        private void linkLabel6_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            About a = new About();
            a.ShowDialog();
        }

        private void trackListToolStripMenuItem_Click(object sender, EventArgs e)
        {
            lbTrackText.Items.Clear();
            RecalcTrackNumbers();
        }

        private void mP3WindowToolStripMenuItem_Click(object sender, EventArgs e)
        {
            lbFileText.Items.Clear();
            RecalcMp3ListNumbers();
        }

        private void RecalcMp3ListNumbers()
        {
            lblNumberOfMP3s.Text = lbFileText.Items.Count + " Items";
        }

        private void clearAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            lbFileText.Items.Clear();
            lbTrackText.Items.Clear();
            RecalcTrackNumbers();
            RecalcMp3ListNumbers();
        }

        private void lnklblResetAll_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            DialogResult dr = MessageBox.Show("Are you sure?", "", MessageBoxButtons.YesNo);
            if (dr == DialogResult.Yes)
            {
                tbTextFile.Text = tbSelection.Text =
                    tbComments.Text = tbCustomGenre.Text = "";
                lbFileText.Items.Clear();
                lbTrackText.Items.Clear();
                RecalcMp3ListNumbers();
                RecalcTrackNumbers();


            }
        }


    }
}